namespace RBAC.Read.Api.Application.Handler.ERP.InboundManagement
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.StorageManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.ERP.InboundManagement;
    using RBAC.Read.Api.Application.Dto.ERP;

    /// <summary>
    /// 采购入库 分页 处理器
    /// </summary>
    public class GetPurchaseStoragePageHandler : IRequestHandler<GetPurchaseStoragePageCommand, APIPaging<PurchaseStorageListDto>>
    {
        private readonly IBaseRepository<PurchaseStorage> repository;
        private readonly ILogger<GetPurchaseStoragePageHandler> logger;

        public GetPurchaseStoragePageHandler(
            IBaseRepository<PurchaseStorage> repository,
            ILogger<GetPurchaseStoragePageHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIPaging<PurchaseStorageListDto>> Handle(GetPurchaseStoragePageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<PurchaseStorageListDto>();
            try
            {
                logger.LogInformation("开始获取采购入库分页 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                var where = BuildWhereClause(request);
                var parameters = BuildParameters(request);

                var (data, total) = repository.GetPaged(request.PageIndex, request.PageSize, where, request.OrderBy, parameters);

                var list = data.Select(o => new PurchaseStorageListDto
                {
                    Id = o.Id,
                    OrderCode = o.OrderCode,
                    OrderDate = o.OrderDate,
                    OrderStatus = o.OrderStatus,
                    BusinessStatus = o.BusinessStatus,
                    Warehouse = o.Warehouse,
                    ArrivalNo = o.ArrivalNo,
                    Operator = o.Operator,
                    Supplier = o.Supplier,
                    BusinessDept = o.BusinessDept,
                    BusinessPerson = o.BusinessPerson,
                    Remark = o.Remark
                }).ToList();

                result.Code = APIEnums.Success;
                result.PageDatas = list;
                result.TotalCount = total;
                result.Msg = "获取采购入库分页成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取采购入库分页失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取采购入库分页失败";
                result.PageDatas = new List<PurchaseStorageListDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        private string BuildWhereClause(GetPurchaseStoragePageCommand request)
        {
            var conditions = new List<string>();
            if (!string.IsNullOrWhiteSpace(request.OrderCode))
            {
                conditions.Add("OrderCode LIKE @OrderCode");
            }
            if (!string.IsNullOrWhiteSpace(request.Warehouse))
            {
                conditions.Add("Warehouse = @Warehouse");
            }
            if (request.StartDate.HasValue)
            {
                conditions.Add("OrderDate >= @StartDate");
            }
            if (request.EndDate.HasValue)
            {
                conditions.Add("OrderDate <= @EndDate");
            }
            return conditions.Count > 0 ? string.Join(" AND ", conditions) : string.Empty;
        }

        private object BuildParameters(GetPurchaseStoragePageCommand request)
        {
            var p = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(request.OrderCode))
            {
                p["OrderCode"] = $"%{request.OrderCode}%";
            }
            if (!string.IsNullOrWhiteSpace(request.Warehouse))
            {
                p["Warehouse"] = request.Warehouse.Trim();
            }
            if (request.StartDate.HasValue)
            {
                p["StartDate"] = request.StartDate.Value.Date;
            }
            if (request.EndDate.HasValue)
            {
                var end = request.EndDate.Value;
                if (end.TimeOfDay == TimeSpan.Zero)
                {
                    end = end.Date.AddDays(1).AddTicks(-1);
                }
                p["EndDate"] = end;
            }
            return p;
        }
    }
}
